package com.chen10.cattle.controller;

import com.chen10.cattle.common.exception.BusinessException;
import com.chen10.cattle.common.protocal.ResponseResult;
import com.chen10.cattle.common.protocal.ResponseVO;
import com.chen10.cattle.model.page.Pager;
import com.chen10.cattle.model.pojo.Cattle;
import com.chen10.cattle.model.vo.*;
import com.chen10.cattle.service.CattleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/api/cattle")
@Slf4j
public class CattleController {
    @Resource
    private CattleService cattleService;

    @Value("${project.avatar-path}")
    private String avatarPath;

    @Value("${server.port}")
    private String serverPort;

    @GetMapping("/list")
    public ResponseVO<List<CattleListVO>> getCattleController() {
        log.info("搜索所有在栏牛只");
        List<CattleListVO> list = null;
        try {
            list = cattleService.getList();
            return ResponseResult.success(list);
        } catch (BusinessException e) {
            return ResponseResult.error(e.getCode(), e.getMessage());
        }
    }

    @GetMapping("/temperatureHistory/{cattleId}")
    public ResponseVO<Pager<TemperatureHistoryVO>> getTemperatureHistory(
            @PathVariable Long cattleId,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "8") Integer pageSize) {
        log.info("获取牛只体温历史，ID: {}, 页码: {}, 每页大小: {}", cattleId, page, pageSize);
        try {
            Pager<TemperatureHistoryVO> result = cattleService.getTemperatureHistory(cattleId, page, pageSize);
            return ResponseResult.success(result);
        } catch (BusinessException e) {
            return ResponseResult.error(e.getCode(), e.getMessage());
        }
    }

    // CattleController.java 新增方法
    // CattleController.java
    @GetMapping("/weightHistory/{cattleId}")
    public ResponseVO<Pager<WeightHistoryVO>> getWeightHistory(
            @PathVariable Long cattleId,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "8") Integer pageSize) {
        log.info("获取牛只体重历史，ID: {}, 页码: {}, 每页大小: {}", cattleId, page, pageSize);
        try {
            Pager<WeightHistoryVO> result = cattleService.getWeightHistory(cattleId, page, pageSize);
            return ResponseResult.success(result);
        } catch (BusinessException e) {
            return ResponseResult.error(e.getCode(), e.getMessage());
        }
    }

    @GetMapping("/locationHistory/{cattleId}")
    public ResponseVO<Pager<LocationHistoryVO>> getLocationHistory(
            @PathVariable Long cattleId,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "8") Integer pageSize) {
        log.info("获取牛只位置历史，ID: {}, 页码: {}, 每页大小: {}", cattleId, page, pageSize);
        try {
            Pager<LocationHistoryVO> result = cattleService.getLocationHistory(cattleId, page, pageSize);
            return ResponseResult.success(result);
        } catch (BusinessException e) {
            return ResponseResult.error(e.getCode(), e.getMessage());
        }
    }
    // 修改获取所有牛只生病记录的接口
    @GetMapping("/allSicknessHistory")
    public ResponseVO<List<SicknessHistoryVO>> getAllSicknessHistory() {
        log.info("获取所有牛只生病记录（不分页）");
        try {
            List<SicknessHistoryVO> result = cattleService.getAllSicknessHistory();
            return ResponseResult.success(result);
        } catch (BusinessException e) {
            return ResponseResult.error(e.getCode(), e.getMessage());
        }
    }

    // 修改获取特定牛只生病记录的接口
    @GetMapping("/sicknessHistory/{cattleId}")
    public ResponseVO<List<SicknessHistoryVO>> getSicknessHistory(
            @PathVariable Long cattleId) {
        log.info("获取牛只生病记录，ID: {}", cattleId);
        try {
            List<SicknessHistoryVO> result = cattleService.getSicknessHistoryNoPaging(cattleId);
            return ResponseResult.success(result);
        } catch (BusinessException e) {
            return ResponseResult.error(e.getCode(), e.getMessage());
        }
    }

    // 添加获取牛只详细信息的接口
    @GetMapping("/detail/{cattleId}")
    public ResponseVO<CattleDetailVO> getCattleDetail(@PathVariable Long cattleId) {
        log.info("获取牛只详细信息，ID: {}", cattleId);
        try {
            CattleDetailVO result = cattleService.getCattleDetail(cattleId);
            return ResponseResult.success(result);
        } catch (BusinessException e) {
            return ResponseResult.error(e.getCode(), e.getMessage());
        }
    }

    // 添加牛只照片上传接口
    @PostMapping("/upload/photo")
    public ResponseVO<String> uploadPhoto(@RequestParam("file") MultipartFile file) {
        log.info("上传牛只照片");
        try {
            // 检查文件是否为空
            if (file.isEmpty()) {
                return ResponseResult.error(400, "文件不能为空");
            }

            // 获取文件名和扩展名
            String originalFilename = file.getOriginalFilename();
            String extension = "";
            if (originalFilename != null && originalFilename.contains(".")) {
                extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            }

            // 检查文件类型
            if (!".jpg".equalsIgnoreCase(extension) && !".jpeg".equalsIgnoreCase(extension)
                    && !".png".equalsIgnoreCase(extension)) {
                return ResponseResult.error(400, "只支持JPG、JPEG和PNG格式的图片");
            }

            // 生成新的文件名
            String newFileName = "niu_" + UUID.randomUUID().toString().replaceAll("-", "") + extension;

            // 确保目录存在
            File dir = new File(avatarPath);
            if (!dir.exists()) {
                dir.mkdirs();
            }

            // 保存文件
            File destFile = new File(avatarPath, newFileName);
            file.transferTo(destFile);

            // 返回访问URL
            String photoUrl = "http://localhost:" + serverPort + "/avatar/" + newFileName;

            return ResponseResult.success(photoUrl);
        } catch (IOException e) {
            log.error("上传文件失败", e);
            return ResponseResult.error(500, "上传文件失败: " + e.getMessage());
        }
    }

    // 添加牛只
    @PostMapping("/add")
    public ResponseVO<Cattle> addCattle(@RequestBody Cattle cattle) {
        log.info("添加牛只: {}", cattle);
        try {
            Cattle result = cattleService.addCattle(cattle);
            return ResponseResult.success(result);
        } catch (BusinessException e) {
            return ResponseResult.error(e.getCode(), e.getMessage());
        }
    }

    // 删除牛只并添加到死亡/出栏记录
    @PostMapping("/delete")
    public ResponseVO<Boolean> deleteCattle(@RequestBody DeathCattleVO deathCattleVO) {
        log.info("删除牛只并添加出栏记录: {}", deathCattleVO);
        try {
            boolean result = cattleService.deleteCattleAndAddDeathRecord(deathCattleVO);
            return ResponseResult.success(result);
        } catch (BusinessException e) {
            return ResponseResult.error(e.getCode(), e.getMessage());
        }
    }
    
    // 获取所有牛只（包括已出栏的）
    @GetMapping("/listAll")
    public ResponseVO<List<CattleManagementVO>> getAllCattleList() {
        log.info("获取所有牛只（包括已出栏的）");
        try {
            List<CattleManagementVO> result = cattleService.getAllCattleList();
            return ResponseResult.success(result);
        } catch (BusinessException e) {
            return ResponseResult.error(e.getCode(), e.getMessage());
        }
    }
}
